package com.choosefine.it.worker.service;

import com.choosefine.it.base.SendPush;
import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.basedata.model.UserInfo;
import com.choosefine.it.basedata.service.CountService;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.choosefine.it.common.utils.Assert;
import com.choosefine.it.common.utils.DateUtils;
import com.choosefine.it.common.utils.IntegerUtil;
import com.choosefine.it.worker.dao.FindWorkMapper;
import com.choosefine.it.worker.model.FindWork;
import com.choosefine.it.worker.model.vo.FindWorkVO;
import com.choosefine.it.worker.model.vo.PublishMgtWorkerVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("findWorkService")
public class FindWorkService{

	@Autowired
	private FindWorkMapper findWorkMapper;
	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private SendPush sendPush;
	@Autowired
	CountService countService;
	/**
	 * 用于第二版根据id 查询详情
	 *  juchengyang 2017年2月14日  update yuxin3.1
	 */
	public FindWorkVO selectByPrimaryKey(Map map) {
		FindWorkVO findWorkVO = null;
		int count = 0 ;
			findWorkVO = new FindWorkVO();
			FindWork returnFindWork = mongoTemplate.findOne(new Query(Criteria.where("_id").is(map.get("publishId"))), FindWork.class);
			count=countService.isInsert(map);
			findWorkVO.setIsInsert(count);
			findWorkVO.setFindWork(returnFindWork);
		return findWorkVO;
	}

	public Page<FindWork> selectByRegionOrType(Map<String, Object> map, PageDTO pageDTO) {
//		page.setTotalSize(findWorkMapper.selectCountByRegionAndWorkType(map));
		//分页
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		Page<FindWork> findWorkMy=findWorkMapper.selectByRegionAndWorkType(map);
		Page<FindWork> findWorkMo=new Page<>();
		if(findWorkMy.size()>0){
			for (int i=0;i<findWorkMy.size();i++){
				FindWork findWorkM=mongoTemplate.findOne(new Query(Criteria.where("_id").is(findWorkMy.get(i).getId())),FindWork.class);
				if(findWorkM!=null){
					UserInfo userInfo = findWorkM.getUserInfo();
					if(userInfo!=null){
					userInfo.setStayYear(DateUtils.getworkeryear(userInfo.getCtime()));
					findWorkM.setUserInfo(userInfo);}
					findWorkMo.add(findWorkM);
				}
			}
		}
		findWorkMo.setPages(findWorkMy.getPages());
		return findWorkMo;
	}



	public Page<PublishMgtWorkerVO> getWorkerPublishmgtInfoByType(Map<String,Object>map,PageDTO pageDTO){
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		return findWorkMapper.getWorkerPublishmgtInfoByType(map);
	}
	
	public List<FindWork> selectWorkerAll(PageDTO pageDTO){
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		Page<FindWork> page = new Page();
		for(FindWork fw:findWorkMapper.selectWorkerAll()){
			page.add(fw);
		}
		return page; 
	}
	public int updateByPrimaryKeySelective(FindWork record) {
		
		return findWorkMapper.updateByPrimaryKey(record);
	}

	/**
	 * 目前应用-控制台-发布管理的状态修改
	 * 
	 * @author liaozhanggen 2016年12月23日
	 */
	public int updatePublishWorkStatusByRecord(FindWork record) {
		record.setUtime(System.currentTimeMillis());
		int num = findWorkMapper.updateByPrimaryKeySelective(record);
		if (num > 0) {
			// 对用户进行推送审核结果的通知
			Integer verifyStatus = record.getVerifyStatus();
			String userCode = record.getUserCode();
			Assert.assertNotNull(userCode, "用户编号为空");
			//暂时未完成     2017/2/15  juchengyang
//			if (verifyStatus == 1) {
//				sendPush.sendPushByUsername(userCode, ConstantDef.MSG_TYPE_PUBLISH_ISVERIFY,
//						record.getDescribe() == null?ConstantDef.MSG_PUSH_PUBLISH_ISVERIFY:record.getDescribe());
//			} else {
//				sendPush.sendPushByUsername(userCode, ConstantDef.MSG_TYPE_PUBLISH_ISNOT_VERIFY,
//						record.getDescribe() == null?ConstantDef.MSG_PUSH_PUBLISH_ISNOT_VERIFY:record.getDescribe());
//			}
			Update update = new Update();
			if (IntegerUtil.isNotNull(record.getVerifyStatus())) {
				update.set("verifyStatus", record.getVerifyStatus());
			}
			if(!StringUtils.isEmpty(record.getReason())){
				update.set("reason", record.getReason());
			}
			update.set("utime", record.getUtime());
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(record.getId())),update , FindWork.class);	
		}
		return num;
	}
	
	/**
	 * 应用于App端的发布信息修改
	 * 
	 * @author liaozhanggen 2016年12月23日
	 */
	public int updatePublishWorkInfo(FindWork record)throws BusinessException {
		if (StringUtils.isEmpty(record.getUserCode())) {
			throw new BusinessException(ResultCode.SERVERERROR_INTERNAL, CommonConstant.WORKER_USERINFO_USERID_IS_NULL);
		}
		if (StringUtils.isEmpty(record.getId())) {
			throw new BusinessException(ResultCode.SERVERERROR_INTERNAL, CommonConstant.WORKER_FINDWORK_ID_IS_NULL);
		}
		record.setUtime(System.currentTimeMillis());
		record.setPublishTime(System.currentTimeMillis());
		record.setVerifyStatus(CommonConstant.VERIFY_STATUS_1);
		//失效发布的工作 或 更新工人发布的求工作信息
		int num = findWorkMapper.updateByPrimaryKeySelective(record);
		if (num > 0) { //如果Mysql操作成功再去操作Mongodb
			Update update = new Update();
			if (null != record.getWorkTypeId()
					/* && 0 != record.getWorkTypeId().intValue()  
					 * 第二版多个工种，此字段改为string
					 * update by juchengyang 2017/2/14
					 */) {
				update.set("workTypeId", record.getWorkTypeId());
			}
			if (!StringUtils.isEmpty(record.getProvinceCode())) {
				update.set("provinceCode", record.getProvinceCode());
			}
			if (!StringUtils.isEmpty(record.getProvinceName())) {
				update.set("provinceName", record.getProvinceName());
			}
			if (!StringUtils.isEmpty(record.getCityCode())) {
				update.set("cityCode", record.getCityCode());
			}
			if (!StringUtils.isEmpty(record.getCityName())) {
				update.set("cityName", record.getCityName());
			}
			if (null != record.getExpectSalary()) {
				update.set("expectSalary", record.getExpectSalary());
			}
			if (!StringUtils.isEmpty(record.getSettleType())) {
				update.set("settleType", record.getSettleType());
			}
			if (null != record.getFirstPhone()) {
				update.set("firstPhone", record.getFirstPhone());
			}
			if (null != record.getSecondPhone()) {
				update.set("secondPhone", record.getSecondPhone());
			}
			update.set(CommonConstant.VERIFY_STATUS, record.getVerifyStatus());
			update.set("utime", record.getUtime());
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(record.getId())),update , FindWork.class);	
		}
		return num;
	}
	
	
	public int deleteWorkerPublishmgtByPrimaryKey(Integer id){
		int num = findWorkMapper.deleteWorkerPublishmgtByPrimaryKey(id);
		if (num > 0) {
			Update update = new Update();
			update.set("isValid", 1);
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(id)),update , FindWork.class);
			update = null;
		}
		return num;
	}

	/**
	 * 查询发布信息明细
	 * 
	 * @author liaozhanggen 2016年12月23日
	 */
	public FindWork queryPublishWorkDetail(Integer publishId) {
		return mongoTemplate.findById(publishId, FindWork.class);
	}
	/**
	 * juchengyang
	 */
	public Page<PublishMgtWorkerVO> selectUserInfoByRealName(String publisher,PageDTO pageDTO){
		PageHelper.startPage(pageDTO.getPageNum(), pageDTO.getPageSize());
		return findWorkMapper.selectUserInfoByRealName(publisher);
	}
	
	public int updateStatusById (Map<String,Object> map){
		int num = findWorkMapper.updateStatusById(map);
		if (num > 0) {
			Update update = new Update();
			if(map.containsKey("isValid")){
				update.set("isValid", map.get("isValid"));
			}
			if(map.containsKey("publishStatus")){
				update.set("publishStatus", map.get("publishStatus"));
			}
			update.set("isValid", 1);
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(map.get("id"))),update , FindWork.class);
			update = null;
		}
		return num;
	}
}
